﻿using jvm.instructions.common;
using jvm.rtda;
using jvm.rtda.frame;
using jvm.rtda.heap;
using jvm.rtda.heap.clazz;
using jvm.rtda.heap.clazz.cp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace jvm.instructions.references
{
    class GET_FIELD : Index16Instruction
    {
        public override void Execute(JFrame frame)
        {
            JMethod method = frame.method;
            JClass curClass = method.jClass;
            JConstantPool pool = curClass.constantPool;
            FieldRef fieldRef = pool.GetConstant<FieldRef>(index);
            JField field = fieldRef.ResolvedField();

            // todo init class
            if (field.Is(AccessFlags.ACC_STATIC))
            {
                Console.WriteLine("java.lang.IncompatibleClassChangeError");
                Environment.Exit(0);
            }

            JOperandStack stack = frame.operandStack;
            JObject obj = stack.PopRef();
            if (obj == null)
            {
                Console.WriteLine("java.lang.NullPointerException");
                Environment.Exit(0);
            }

            char descriptor = field.descriptor[0];
            uint slotId = field.slotId;
            Slots slots = obj.Fields;
            switch (descriptor)
            {
                case 'Z':
                case 'B':
                case 'C':
                case 'S':
                case 'I':
                    stack.PushInt(slots.GetInt(slotId));
                    break;
                case 'F':
                    stack.PushFloat(slots.GetFloat(slotId));
                    break;
                case 'J':
                    stack.PushLong(slots.GetLong(slotId));
                    break;
                case 'D':
                    stack.PushDouble(slots.GetDouble(slotId));
                    break;
                case 'L':
                case '[':
                    stack.PushRef(slots.GetRef(slotId));
                    break;
            }
        }
    }
}
